﻿Public Class HukTaahhutIsyeri : Inherits Process

	Dim Borc As Prim.Borc.BorcIsyeri

	Public Overrides Sub GenericEvent(ByVal e As ProcessEventArgs)
		Select Case e.EventType
			Case EventType.Initialize
				Start("İşyeri taahhütleri", "İşyeri bilgisini girin.")
				AddIsyeri()
				StartBody()
				AddReport()
			Case EventType.ValidateForm
				Tables.Clear()
				Tables.Add("isyeri", Isyeri.IsyeriNoAra(Remote, Input("Isyeri")))
				Rs = Hukuk.Taahhut.GenelIsyeriOku(Local, Input("Isyeri"))
				If Not Rs.EOF Then
					'Taahhüt kaydı var
					Dim Answer As String = Ask("Bu işyerinin taahhüt kaydı yapılmıştır. Ne yapmak istiyorsunuz?", "1|Taahhüt çizelgesini göster;2|Tarihlerde değişiklik yap;3|Taahhüt çizelgesini sil")
					If Answer = "" Then Focus("Isyeri") : Return
					If Answer = "1" Then
						Dim Process As New TaahhutCizelgesiIsyeri
						Process.Arguments.Add("isyerino", Tables("isyeri")("isyerino"))
						Window.Launch(Process)
						Return
					ElseIf Answer = "2" Then
					ElseIf Answer = "3" Then
						If Not Confirm("Dikkat! Taahhüt çizelgesini silerseniz, bu değişikliği geri alamazsınız. Devam etmek istediğinize emin misiniz?") Then Return
						Hukuk.Taahhut.OdemePlaniIsyeriSil(Local, 2011, Input("Isyeri"))
						Info("Taahhüt çizelgesi silinmiştir.")
						Close()
						Return
					End If
				Else
					'Taahhut kaydı yok
					Dim Text As String = ""
					Rs = Hukuk.Af.TaksitIsyeriOku(Local, 2008, Input("Isyeri"))
					If Not Rs.EOF Then Text &= " ve 2008"
					Rs = Hukuk.Af.TaksitIsyeriOku(Local, 2009, Input("Isyeri"))
					If Not Rs.EOF Then Text &= " ve 2009"
					If Text <> "" Then Warning("Bu işyeri " & Mid(Text, 5) & " yılındaki aftan yararlanmıştır.")
					Dim Answer As String = Ask("Ne yapmak istiyorsunuz?", "1|Borcunu otomatik hesapla;2|Borcu hesaplama, elden girilecek")
					If Answer = "" Then Focus("Isyeri") : Return
					If Answer = "1" Then
						Help = "Prim borcu hesaplanıyor..."
						Borc = Prim.Borc.HesaplaIsyeri(Remote, Input("Isyeri"), "1976/01/01", "2011/06/30", Today)
						If Borc.ErrorMessage <> "" Then
							Warning(Borc.ErrorMessage)
							ResetForm()
							Return
						End If
						If Borc.Aylar.Count = 0 Then
							Warning("İşyerinin ilgili dönemlere ait borcu bulunamadı.")
							ResetForm()
							Return
						End If
					Else
						Borc = New Prim.Borc.BorcIsyeri
						Borc.Token = Remote
						Borc.Start(Input("Isyeri"), Today)
					End If
					ManuelBorcGoster()
				End If
				e.Result = True
			Case EventType.Edit
				Dim Process As New IsyeriTaahhutBordrolar
				Process.isyerino = Tables("isyeri")("isyerino")
				Process.Run(Window)
				If Not Process.Result Then Return
				ManuelBorcGoster()
			Case EventType.Save
				ShowDialog("Donem")
			Case EventType.PageHeader
				Report.PrintReportInfo("İŞYERİ PRİM BORCU DÖKÜMÜ", FormatIsyeriNo(Tables("isyeri")("isyerino")) & " - " & Trim(Tables("isyeri")("isyeriadi")))
				Report.SetColumns("Tarih;Bordro;Kişi;PEK;Anapara;Elden", "2;1;1;2;2;1", "d;c;n;m;m;c", "--")
			Case EventType.ReportDetail
				Dim Toplam(3) As Decimal
				For Each Ay As Prim.Borc.Borc.Ay In Borc.Aylar.Values
					For Each Bordro In Ay.Bordrolar
						Report.Print(Ay.Tarih, Bordro.tip, Bordro.yatirimlar.Count, Bordro.pek, Bordro.anapara, If(Bordro.virtual, "*", ""))
						Toplam(0) += Bordro.anapara
					Next
				Next
				Report.PrintTotal("<cs=4><l>TOPLAM", Toplam(0), "")
		End Select
	End Sub

	Sub ManuelBorcGoster()
		Rs = Hukuk.Taahhut.IsyeriBordroOku(Local, Input("Isyeri"))
		For Each bordro In Borc.Bordrolar.ToArray
			If bordro.virtual Then Borc.Bordrolar.Remove(bordro)
		Next
		For Each Row In Rs
			Borc.BordroEkle(Rs("bordrotar"), Rs("bordro"), Rs("pek"))
		Next
		Borc.DonemlereAyir()
		Report.Restart()
		Help = "Bordroları düzenlemek için Düzenle butonunu, taksitlendirmeye devam etmek için Devam butonunu kullanın."
		Buttons.Show("Edit.Next.Reset")
	End Sub

	Public Overrides Sub DialogEvent(e As ProcessEventArgs)
		Select Case Modal.Name
			Case "Donem" : DonemDialog(e)
			Case "Taksit" : TaksitDialog(e)
		End Select
	End Sub


#Region " Taksit dağıtımı "

	Public WithEvents Grid As Grid
	Dim FirstDate, LastDate As Date
	Dim BorcListesi As New List(Of Decimal)

	Public Sub TaksitDialog(e As ProcessEventArgs)
		Select Case e.EventType
			Case EventType.Initialize
				Modal.Start("Taksit dağılımı", "Taksitlerin ödeneceği ayları belirleyin.")
				Modal.AddList()
				Modal.CustomSize = New Size(750, 420)
			Case EventType.Shown
				Grid = Modal.List
				Grid.RowHeadersWidth = 50
				Grid.RowHeadersVisible = True
				Grid.AddColumns("01(Ocak;c;5%),02(Şubat;c;5%),03(Mart;c;5%),04(Nisan;c;5%),05(Mayıs;c;5%),06(Haziran;c;5%)")
				Grid.AddColumns("07(Temmuz;c;5%),08(Ağustos;c;5%),09(Eylül;c;5%),10(Ekim;c;5%),11(Kasım;c;5%),12(Aralık;c;5%)")
				Grid.CellBorderStyle = DataGridViewCellBorderStyle.Single
				Grid.SelectionMode = DataGridViewSelectionMode.CellSelect
				Grid.Sortable = False
				Grid.RowTemplate.Height = 48
				Grid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None
				Grid.AddButton("oto-", "Otomatik dağıt")
				Grid.AddButton("remove", "Dönem (-)")
				Grid.AddButton("add-", "Dönem (+)")
				Grid.AddButton("ayl", "Aralık (-)")
				Grid.AddButton("ayr", "Aralık (+)")
				FirstDate = New Date(Today.AddMonths(1).Year, Today.AddMonths(1).Month, 1)
				ShowDates()
				Modal.Buttons.Show("Back.Next")
			Case EventType.Other
				Select Case e.Name
					Case "List.oto"
						If Not Confirm("Borç otomatik olarak 24 aya dağıtılacak. Devam etmek istiyor musunuz?") Then Return
						Dim MD As Integer = DateDiff(DateInterval.Month, FirstDate, LastDate) + 1
						Dim Interval = If(BorcListesi.Count = 1, 1, (MD - 1) / (BorcListesi.Count - 1))
						For i = 0 To MD - 1
							TaksitCount(FirstDate.AddMonths(i)) = 0
						Next
						Dim c As Decimal = 0
						For i = 0 To BorcListesi.Count - 1
							TaksitCount(FirstDate.AddMonths(Math.Round(c))) += 1
							c += Interval
						Next
						Recalculate()
					Case "List.add"
						SetCellValue("+")
					Case "List.remove"
						SetCellValue("-")
					Case "List.ayl"
						FirstDate = FirstDate.AddMonths(-1)
						ShowDates()
					Case "List.ayr"
						FirstDate = FirstDate.AddMonths(1)
						ShowDates()
				End Select
			Case EventType.Save
				Dim Taksitler As New SortedList(Of Date, Integer)
				Dim c As Integer = 0
				For Each Row As DataGridViewRow In Grid.Rows
					For Each Cell As DataGridViewCell In Row.Cells
						If Val(Cell.Value) > 0 Then
							Taksitler.Add(New Date(Row.HeaderCell.Value, Cell.ColumnIndex + 1, 1), Cell.Value)
							c += Val(Cell.Value)
						End If
					Next
				Next
				If c < BorcListesi.Count Then Warning("Tüm dönemleri girmediniz. Kalan " & (BorcListesi.Count - c) & " dönemi girdikten sonra kaydedebilirsiniz.") : Return
				If Not Confirm("Ödeme planı kaydedilecek. Devam etmek istediğinize emin misiniz?") Then Return
				Kaydet(Taksitler)
		End Select
	End Sub

	Sub Kaydet(Taksitler As SortedList(Of Date, Integer))
		Dim i As Integer = -1, c As Integer = 0, d As Date
		For Each Donem In Borc.Donemler.Values
			If Donem.Aktif Then
				Donem.OdemeTarihi = Today.Date
				If c = 0 Then
					i += 1
					c = Taksitler.Values(i)
					d = Taksitler.Keys(i)
				End If
				c -= 1
				Donem.OdemeTarihi = d
				For Each b In Donem.Aylar
					For Each a In b.Bordrolar
						a.ceza = a.anapara * Prim.GecikmeZammiHesabi(a.tip, a.tarih, d) / 100
					Next
				Next
			End If
		Next
		Hukuk.Taahhut.KaydetIsyeri(Local, Tables("isyeri")("isyerino"), Borc, User.Kaykul)
		Info("Taahhüt çizelgesi kaydedildi.")
		Dim Process As New TaahhutCizelgesiIsyeri
		Process.Arguments.Add("isyerino", Tables("isyeri")("isyerino"))
		Window.Launch(Process)
	End Sub

	Sub ShowDates()
		Grid.Rows.Clear()
		LastDate = FirstDate.AddMonths(23)
		For i As Integer = FirstDate.Year To LastDate.Year
			Dim Row = Grid.AddRow()
			Row.HeaderCell.Value = i
			Row.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
			For j = 1 To 12
				Dim M = i & Format(j, "00")
				If M < FirstDate.ToString("yyyyMM") Or M > LastDate.ToString("yyyyMM") Then Row.Cells(j - 1).Value = "x"
			Next
		Next
	End Sub

	Property TaksitCount(d As Date) As Integer
		Get
			Dim Cell = (From r As DataGridViewRow In Grid.Rows Where r.HeaderCell.Value = d.Year).First.Cells(d.Month - 1)
			Return Val(Cell.Value)
		End Get
		Set(Value As Integer)
			Dim Cell = (From r As DataGridViewRow In Grid.Rows Where r.HeaderCell.Value = d.Year).First.Cells(d.Month - 1)
			Cell.Value = If(Value = 0, "", Trim(Value))
		End Set
	End Property

	Private Sub Grid_CellPainting(sender As Object, e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles Grid.CellPainting
		If e.RowIndex >= 0 And e.ColumnIndex >= 0 Then
			Dim R As Rectangle = e.CellBounds
			Dim Font As New Font(Me.Font.Name, Me.Font.Size - 2)
			e.Graphics.FillRectangle(Brushes.White, R)
			R.Inflate(-1, -1)
			R.Width += 1 : R.Height += 1
			e.Graphics.FillRectangle(SystemBrushes.ButtonShadow, R)
			R.Inflate(-1, -1)
			If e.FormattedValue = "x" Then
				e.Graphics.FillRectangle(New Drawing2D.HatchBrush(Drawing2D.HatchStyle.LightUpwardDiagonal, Color.DarkGray, Color.White), R)
			Else
				e.Graphics.FillRectangle(Brushes.White, R)
			End If
			If (e.State And DataGridViewElementStates.Selected) > 0 Then e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(128, SystemColors.Highlight)), R)
			If e.FormattedValue <> "x" Then
				R.Inflate(-3, -3)
				e.Graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.ClearTypeGridFit
				Dim Text As String = Fm(Grid.Rows(e.RowIndex).Cells(e.ColumnIndex).Tag)
				If Val(e.Value) > 1 Then Text &= vbCrLf & "(" & e.Value & " dönem)"
				e.Graphics.DrawString(Text, Font, Brushes.Black, R, StrFormat("mr"))
			End If
			e.Handled = True
		End If
	End Sub

	Sub SetCellValue(d As String)
		If Grid.CurrentCell.Value = "x" Then
			Warning("Bu tarihe taksit koyamazsınız.")
			Return
		End If
		If d = " " Then
			Grid.CurrentCell.Value = If(Grid.CurrentCell.Value = "", "1", "")
		ElseIf d = "+" Then
			Grid.CurrentCell.Value = Trim(Val(Grid.CurrentCell.Value) + 1)
		ElseIf d = "-" Then
			Grid.CurrentCell.Value = If(Val(Grid.CurrentCell.Value) > 0, Trim(Val(Grid.CurrentCell.Value) - 1), "")
		Else
			Grid.CurrentCell.Value = d
		End If
		Recalculate()
	End Sub

	Sub Recalculate()
		Dim c As Integer = 0
		For Each Row As DataGridViewRow In Grid.Rows
			For Each Cell As DataGridViewCell In Row.Cells
				If Cell.Value = "" Then
					Cell.Tag = ""
				Else
					Cell.Tag = 0
					For i = 1 To Val(Cell.Value)
						If c < BorcListesi.Count Then Cell.Tag += BorcListesi(c)
						c += 1
					Next
				End If
			Next
		Next
		Grid.Invalidate()
	End Sub

	Private Sub Grid_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Grid.KeyDown
		If e.KeyCode = Keys.Space Then
			SetCellValue(" ")
			e.Handled = True
		ElseIf e.KeyCode = Keys.Add Then
			SetCellValue("+")
			e.Handled = True
		ElseIf e.KeyCode = Keys.Subtract Then
			SetCellValue("-")
			e.Handled = True
		End If
	End Sub

#End Region

#Region " Dönem kısıtlaması "

	Public donem01, donem02 As Input
	Public donem11, donem12 As Input

	Public Sub DonemDialog(ByVal e As ProcessEventArgs)
		Select Case e.EventType
			Case EventType.Initialize
				Modal.Start("İşyeri taahhütleri", "Taksitlendirilecek dönem aralığını girin.")
				Dim List As String = ""
				For Each Donem In Borc.Donemler.Values
					List &= "|" & Donem.Donem
				Next
				donem01 = Modal.AddCombo("donem01", "Aralık (SSY için)", Mid(List, 2), "", "--first--")
				donem02 = Modal.AddCombo("donem02", "", Mid(List, 2), "nl", "--last--")
				donem11 = Modal.AddCombo("donem11", "Aralık (SGY için)", Mid(List, 2), "", "--first--")
				donem12 = Modal.AddCombo("donem12", "", Mid(List, 2), "nl", "--last--")
			Case EventType.Shown
				Modal.Buttons.Show("Next")
			Case EventType.Save
				For Each Donem In Borc.Donemler.Values
					For Each Ay In Donem.Aylar
						For Each Bordro In Ay.Bordrolar
							If donem11 Is Nothing Then
								Bordro.aktif = Donem.Donem >= donem01.get AndAlso Donem.Donem <= donem02.get
							Else
								Select Case Len(Bordro.tip)
									Case "1" : Bordro.aktif = Donem.Donem >= donem01.get AndAlso Donem.Donem <= donem02.get
									Case "2" : Bordro.aktif = donem11 Is Nothing OrElse (Donem.Donem >= donem11.get AndAlso Donem.Donem <= donem12.get)
								End Select
							End If
						Next
					Next
				Next
				For Each Donem In Borc.Donemler.Values
					If Donem.Aktif Then
						BorcListesi.Add(Donem.Anapara)
					End If
				Next
				Modal.Close()
				ShowDialog("Taksit")
		End Select
	End Sub

#End Region

End Class

Class IsyeriTaahhutBordrolar : Inherits ProcessDialog

	Public isyerino As String

	Public Overrides Sub GenericEvent(ByVal e As ProcessEventArgs)
		Select Case e.EventType
			Case EventType.Initialize
				Start("Bordro düzenleme", "Ekle ve Sil butonlarıyla bordro ekleyip çıkarabilirsiniz.")
				AddList()
				List.AddColumns("bordrotar(Bordro Tarihi;d;95%),bordro(Bordro;c;55%),pek(PEK Toplamı;m;90%)")
				SetSize(512, 512)
			Case EventType.Shown
				Dim Rs = Hukuk.Taahhut.IsyeriBordroOku(Local, isyerino)
				List.DataSource = Rs
				Buttons.Show("Add.Delete.Save")
			Case EventType.Add
				Do
					Dim Process As New IsyeriTaahhutBordro
					Process.List = List
					Process.Run(Me.Parent)
					If Not Process.Result Then Exit Do
					Modified = True
				Loop
			Case EventType.Delete
				If List.SelectedRows.Count = 0 Then Exit Sub
				If Not Confirm("Bu kaydı silmek istediğinizden emin misiniz?") Then Exit Sub
				Modified = True
				List.RemoveSelected()
			Case EventType.Save
				Hukuk.Taahhut.IsyeriBordroKaydet(Local, isyerino, List)
				ReturnResult(True)
		End Select
	End Sub

End Class

Class IsyeriTaahhutBordro : Inherits ProcessDialog

	Public Shadows List As Grid

	Dim Bordro As Object = Split("D;D1;D2;E;C;H;L;X;Y", ";")

	Public Overrides Sub GenericEvent(ByVal e As ProcessEventArgs)
		Select Case e.EventType
			Case EventType.Initialize
				Start("Bordro girişi", "Bordro tarihini ve ilgili bordroların PEK toplamını girin.")
				For i = 0 To 9
					AddField("tarih" & i & ":AyYil[label=Bordro tarihi]", "")
					AddCombo("bordro" & i, "Bordro", "D|D1|D2|E|C|H|L|X|Y", "")
					AddMoney("tutar" & i, " PEK toplamı", "nl")
				Next
				SetSize(600, 450)
			Case EventType.Shown
				Buttons.Show("Save")
			Case EventType.Save
				For i = 0 To 9
					If Not IsEmpty("tarih" & i) Then
						If Check("tarih" & i, Not IsValidDate(Input("tarih" & i)), "Bordro tarihi geçersiz.") Then Return
						If Check("bordro" & i, IsEmpty("bordro" & i), "Bordro tipini girmeniz gerekir.") Then Return
					End If
				Next
				For i = 0 To 9
					If Not IsEmpty("tarih" & i) Then
						Result = True
						List.AddRow(New Date(Mid(Input("tarih" & i), 3, 4), Mid(Input("tarih" & i), 1, 2), 1), Input("bordro" & i), Input("tutar" & i))
					End If
				Next
				Close()
		End Select
	End Sub

	Function IsValidDate(Text As String) As Boolean
		If Len(Text) <> 6 Then Return False
		Dim Ay As Integer = Val(Mid(Text, 1, 2))
		If Ay < 1 Or Ay > 12 Then Return False
		Dim Yil As Integer = Val(Mid(Text, 3, 4))
		Return True
	End Function

End Class

